package proj.unions.resource;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import proj.unions.general.L;
import proj.unions.general.OnMyCallBack;
import proj.unions.general.SuperTools;
import android.accounts.NetworkErrorException;
import android.app.Activity;

public class DealOldRes implements Runnable, RMConstDefine {

	private Activity mActivity = null;
	private OnMyCallBack mOnMyCallBack = null;
	
	private String mVer = "";
	
	public DealOldRes(Activity a, OnMyCallBack l)
	{
		mActivity = a;
		mOnMyCallBack = l;
		mVer = SuperTools.getInstance().getAPKPath() + "ver";
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		check();
		//重新创建log目录
		L.init();
		//拷贝music文件夹
		checkMusicFile();
		mOnMyCallBack.onReceive("", -1, null);
	}

	private void check()
	{
		String localVersion = "";
		try {
			localVersion = readVersionCode();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String curVersion = SuperTools.getInstance().getVersionCode();
		L.d("==========localVersion:" +localVersion);
		L.d("==========curVersion:" +curVersion);
		
		//如果本地版本为空,或者本地版本小于当前版本,则删除资源
		if(localVersion.equals("") || Integer.valueOf(localVersion) < Integer.valueOf(curVersion))
		{
			//判断是否asset data不存在
			boolean isDeleteData = false;
			try {
				String[] ff = mActivity.getAssets().list("");
				for (String f : ff) 
				{
				    if (f.equals("data") && f.length() == 4) 
					{
				    	isDeleteData = true;
				    	break;
			        }
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			//删除资源
			if (isDeleteData)
			{
				String path = SuperTools.getInstance().getAPKPath();
				SuperTools.getInstance().deleteFile(path);
				File newFile = new File(path);
				newFile.mkdirs();
			}
			
			try {
				writeVersionCode(curVersion);		
				SuperTools.getInstance().writeLocalFile(KEY_CLIENT_VERSION_RES, "");
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	private void writeVersionCode(String versionCode) throws IOException
	{
		File f = new File(mVer);
		SuperTools.getInstance().deleteFile(mVer);
		f.createNewFile();
		FileOutputStream fos = new FileOutputStream(f);
		fos.write(versionCode.getBytes());
		fos.flush();
		fos.close();
	}
	
	private String readVersionCode() throws IOException
	{
		File f = new File(mVer);   
		InputStream is = new FileInputStream(f);
	
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int count = 0;
		byte[] buffer = new byte[1024];
		while((count = is.read(buffer)) != -1)
		{
			bos.write(buffer, 0, count);
		}
		String localVersion = bos.toString();
		bos.close();
		return localVersion;
	}
	
	private void checkMusicFile()
	{
		boolean flag = false;
		boolean flag2 = false;
		String SDMusicPath = SuperTools.getInstance().getDownloadResPath() + "music/";
		String SDOtherPath = SuperTools.getInstance().getDownloadResPath() + "other/";
		File file = new File(SDMusicPath);
		if(!file.exists())
		{
			file.mkdirs();
			flag = true;
			L.d("fuck create newFile music success");
		}
		File file2 = new File(SDOtherPath);
		if(!file2.exists())
		{
			file2.mkdirs();
			flag2 = true;
			L.d("fuck create newFile other success");
		}
		
		if (flag == true || flag2 == true)
		{
			//copy asset里的music文件夹to SD卡
			String[] ff;
			try {
				ff = mActivity.getAssets().list("");
				for (String f : ff) 
				{
				    if (f.equals("data") && f.length() == 4) 
					{
				    	L.d("=======what the fuck music? fileName:" + f);
				    	if(flag == true)
				    	{
				    		String[] musicList = mActivity.getAssets().list(f + "/music");
				    		traverseFile(f + "/music", musicList);
				    	}
				    	if(flag2 == true)
				    	{
				    		String[] otherList = mActivity.getAssets().list(f + "/other");
				    		traverseFile(f + "/other", otherList);
				    	}
			        }
				}	
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				L.d("=======checkMusicFile error");
			}
		}
	}
	
	private void traverseFile(String lastpath, String[] fileList) throws IOException
	{
		if(fileList == null || fileList.length <= 0)
			return;
		String sdCardPath = SuperTools.getInstance().getAPKPath();
		for (String f : fileList) 
		{
			if(f.indexOf(".") >= 0)//文件
			{
				try {
					copyFileFromAssets(lastpath + "/" + f, sdCardPath + lastpath + "/" + f);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					L.d("文件 :" + /*sdCardPath +*/ lastpath + "/" + f + "拷贝不成功");
				}
				L.d("文件 :" + /*sdCardPath +*/ lastpath + "/" + f + "拷贝成功");
			}
			else//文件夹
			{
				traverseFile(lastpath + "/" + f, mActivity.getAssets().list(lastpath + "/" + f));
			}
		}
	}
	
	private void copyFileFromAssets(String srcFile, String targetFile) throws IOException
	{
		File f = new File(targetFile);
		if (f.exists())
			f.delete();
		if (!f.getParentFile().exists()) 
			f.getParentFile().mkdirs();
		
		byte[] buffer = new byte[2048];
		int byteReaded = 0;
		f.createNewFile();

		InputStream is = mActivity.getAssets().open(srcFile);
		if(is != null)
		{
			FileOutputStream fos = new FileOutputStream(f);
			do {
				try {
					byteReaded = is.read(buffer);
				} catch (IOException e) {
					try {
						throw new NetworkErrorException(e);
					} catch (NetworkErrorException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				if (byteReaded > 0) {
					fos.write(buffer, 0, byteReaded);
				}
				fos.flush();
			} while (byteReaded != -1);
			fos.close();
		}
		is.close();
	}
	
}
